package web

import (
	"net/http"

	"gitee.com/thubcc/mobile/fm"
	"gitee.com/thubcc/mobile/utils"
	"gitee.com/thubcc/rtlmmap"
	"github.com/gin-gonic/gin"
	"github.com/hajimehoshi/oto"
	"github.com/prometheus/common/log"
)

var (
	otoc *oto.Context
)

func GetOtoContext() *oto.Context {
	return otoc
}

func init() {
	var err error
	otoc, err = oto.NewContext(48000, 2, 2, 960*50)
	if err != nil {
		log.Error(err)
	}
}

type FMView struct {
	view   utils.RFInterface
	fm     *fm.FM
	player *oto.Player
	freq   float64
	fafc   func(float64)
}

func NewFMV(view *rtlmmap.FTView) (*FMView, error) {
	f := 200. / 1920.
	fafc := func(df float64) {
		ftco := view.View.GetFTco()
		_, dfr := ftco.GetTuner()
		ff := df / dfr
		ftco.PPMAbs(ff)
	}
	return &FMView{view: view, fm: fm.NewFM(f, 2, view), freq: 0.0, fafc: fafc}, nil
}

func (view *FMView) Start() {
	go func() {
		view.player = otoc.NewPlayer()
		view.fm.Start(view.player)
	}()
}

func (view *FMView) Stop(c *gin.Context) {
	view.fm.Close()
}

func (view *FMView) AFC(c *gin.Context) {
	var on bool
	if c.Query("on") == "true" {
		on = true
	} else {
		on = false
	}
	view.fm.AFC(on, view.fafc)
}

func NewFMVWithHandle(c *gin.Context) *FMView {
	port, _ := CommonParam(c)
	config := &rtlmmap.DefaultFMConfig
	v := rtlmmap.NewRtlView(port, config).FTV(port)
	v.ResetPPM()
	fmv, err := NewFMV(v)
	if err != nil {
		c.JSON(http.StatusOK, Response{nil, err})
		return nil
	}
	fmv.Start()
	c.JSON(http.StatusOK, Response{nil, nil})
	return fmv
}
